<template>
  <div class="app-container">
    <el-tree
      :data="categoryList"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ data.name }}</span>
        <span>
          <el-button
            type="text"
            size="mini"
            @click="() => edit(data)">
            编辑
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'CategoryTree',
  data() {
    return {
      categoryList: []
    }
  },
  mounted() {
    this.getCategoryList()
  },
  methods: {
    /**
     * 分类列表
     */
    getCategoryList() {
      api.category.tree().then(response => {
        this.categoryList = response.data
      })
    },
    /**
     * 修改
     * @param row
     */
    edit(data) {
      this.$router.push({
        path: `/product/category/edit/${data.id}`
      })
    },
    /**
     * 删除
     * @param row
     */
    remove(node, data) {
      this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.category.remove({ id: data.id }).then(response => {
          this.$message({
            message: response.message || '删除成功',
            type: 'success'
          })
          this.$router.push({
            path: `/product/category/tree?t=${new Date().getTime()}`
          })
        })
      }).catch(() => {})
    }
  },
  /**
   * 刷新
   * @param to
   * @param from
   * @param next
   */
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      const newQuery = Object.assign({}, to.query)
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getCategoryList()
      }
    }
    next()
  }
}
</script>

<style scoped lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 10px;
}
</style>

